package top.xiaozhaobk.xiaofenshu.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import top.xiaozhaobk.xiaofenshu.gateway.constant.RedisKeyConstants;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private ObjectMapper objectMapper;

    @SneakyThrows
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        log.info("## 用户权限列表，loginId:{},loginType:{}", loginId, loginType);

        String userRoleKey = RedisKeyConstants.buildUserRoleKey(Long.valueOf(loginId.toString()));
        String userRoleValue = (String)redisTemplate.opsForValue().get(userRoleKey);

        if (StringUtils.isBlank(userRoleValue)) {
            return null;
        }

        // 将 JSON 字符串转换为 List<String> 集合
        List<String> userRoleKeys  = objectMapper.readValue(userRoleValue, new TypeReference<>() {});
        if (CollUtil.isNotEmpty(userRoleKeys)) {
            List<String> rolePermissionsKeys  = userRoleKeys.stream().map(RedisKeyConstants::buildRolePermissionsKey).toList();

            List<Object> rolePermissionsValues  = redisTemplate.opsForValue().multiGet(rolePermissionsKeys);
            if (CollUtil.isNotEmpty(rolePermissionsValues)) {
                List<String> permissions = Lists.newArrayList();
                rolePermissionsValues.forEach(jsonValue -> {
                    try {
                        List<String> rolePermissions  = objectMapper.readValue(jsonValue.toString(), new TypeReference<>() {
                        });
                        permissions.addAll(rolePermissions);
                    }catch (JsonProcessingException e) {
                        log.error("==> JSON 解析错误: ", e);
                    }
                });
                return permissions;
            }
        }
        // todo 从 redis 获取

        return null;
    }

    @SneakyThrows
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        log.info("## 获取用户角色列表, loginId: {}", loginId);

        // 构建 用户-角色 Redis Key
        String userRolesKey = RedisKeyConstants.buildUserRoleKey(Long.valueOf(loginId.toString()));

        // 根据用户 ID ，从 Redis 中获取该用户的角色集合
        String useRolesValue = (String) redisTemplate.opsForValue().get(userRolesKey);

        if (StringUtils.isBlank(useRolesValue)) {
            return null;
        }

        // 将 JSON 字符串转换为 List<String> 集合
        return objectMapper.readValue(useRolesValue, new TypeReference<>() {});
    }
}
